package com.atguigu.flink.chapter06;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.ArrayList;

public class WindowDemo4 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env.socketTextStream("hadoop102",8888)
                .flatMap(new FlatMapFunction<String, Tuple2<String,Integer>>() {
                    @Override
                    public void flatMap(String s,
                                        Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] words = s.split(" ");
                        for (String word : words) {
                            out.collect(Tuple2.of(word,1));
                        }
                    }
                })
                .keyBy(t -> t.f0)
                //基于个数的滚动窗口
                //.countWindow(5)
                //基于个数的滑动窗口：窗口长度5（最多5个窗口）  2：每来2个触发一次计算
                .countWindow(5,2)
                //窗口处理函数：如何处理窗口中的元素？
                /*
                参数1：输入
                参数2：输出
                参数3：key的类型
                参数4： 全局窗口
                 */
                .process(new ProcessWindowFunction<Tuple2<String, Integer>, String, String, GlobalWindow>() {
                    @Override
                    public void process(String key,  //窗口所属的key
                                        Context ctx, //上下文对象：获取窗口的开始时间和结束时间
                                        Iterable<Tuple2<String, Integer>> elements, //集合：存储窗口中的所有元素
                                        Collector<String> out) throws Exception {
                        ArrayList<String> list = new ArrayList<>();
                        for (Tuple2<String, Integer> t : elements) {
                            list.add(t.f0 + "_" + t.f1);
                        }
                        String msg = list + "";
                        out.collect(msg);
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

